package com.qfmy.service.impl.common;

import com.qfmy.config.ThreadPoolConfig;
import com.qfmy.mapper.common.UserSignInMapper;
import com.qfmy.mapper.user.UserInfoMapper;
import com.qfmy.service.common.UserSignInService;
import com.qfmy.vo.common.UserSignInVo;
import common.exception.BaseException;
import common.login.LoginUser;
import common.login.LoginUserHolder;
import common.result.ResultCodeEnum;
import model.entity.common.UserSignIn;
import model.enums.common.SignInStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;

/**
 * @author 清风明月
 * @Package com.qfmy.service.impl.common
 * @date 2025/5/18
 * @description 签到表
 */
@Service
@SuppressWarnings("all")
public class UserSignInServiceImpl implements UserSignInService {

    /**
     *  注入mapper
     */
    @Autowired
    private UserSignInMapper signInMapper;
    /**
     * 注入用户的mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 签到
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signIn() {
        //获取当前用户id
        Long userId = getUserId();
        //根据用户id获取用户签到信息
        UserSignIn userSignIn = signInMapper.selectOne(userId);
        //判断是否为空
        if (userSignIn == null) {
            //创建用户签到信息
            userSignIn = new UserSignIn();
            userSignIn.setUserId(userId);
            userSignIn.setSignInStatus(SignInStatus.HAS_SIGN_IN.getCode());
            userSignIn.setContinuous(true);
            userSignIn.setConsecutiveDays(1);
            //获取当前日期并且对日期进行格式化年月日
            String formattedDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            userSignIn.setSignInDate(String.valueOf(LocalDate.parse(formattedDate)));
            //插入用户签到信息
            signInMapper.insertUserSignIn(userSignIn);
        }else
        {
            //判断用户是否已经签到
            //获取当前日期并且对日期进行格式化年月日
            String formattedDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String day = String.valueOf(LocalDate.parse(formattedDate));
            //判断用户是否已经签到
            if (userSignIn.getSignInDate().equals(day)) {
                throw new BaseException(ResultCodeEnum.HAS_SIGN_IN);
            }
            //判断是否连续签到
            Integer signInDate = Integer.parseInt(userSignIn.getSignInDate().replace("-", ""));
            Integer day1 = Integer.parseInt(day.replace("-", ""));
            //如果当前时间与签到的时间相差超过了1天则重置连续签到天数为1
            if(signInDate + 1 != day1)
            {
                userSignIn.setConsecutiveDays(1);
            }else
            {
                userSignIn.setConsecutiveDays(userSignIn.getConsecutiveDays() + 1);
            }
            //设置签到状态
            userSignIn.setSignInStatus(SignInStatus.HAS_SIGN_IN.getCode());
            //设置连续签到
            userSignIn.setContinuous(true);
            //设置签到日期
            userSignIn.setSignInDate(day);
            //更新用户签到信息
            signInMapper.updateUserSignIn(userSignIn);
        }

        //异步调用用户信息进行更新余额
        CompletableFuture.runAsync(() -> {
            //更新用户余额
            userInfoMapper.updateBanlance(userId);
        }, ThreadPoolConfig.executorService);
    }

    /**
     * 是否签到
     * @return
     */
    @Override
    public UserSignInVo isSignIn() {
        //获取当前用户id
        Long userId = getUserId();
        //根据用户id获取用户签到信息
        UserSignIn userSignIn = signInMapper.selectOne(userId);
        //判断是否为空
        if (userSignIn == null) {
            //创建用户签到信息
            userSignIn = new UserSignIn();
            userSignIn.setUserId(userId);
            userSignIn.setSignInStatus(SignInStatus.NOT_SIGN_IN.getCode());
            userSignIn.setContinuous(false);
            userSignIn.setConsecutiveDays(0);
            //拷贝数据
            UserSignInVo userSignInVo = Copy(userSignIn);
            return userSignInVo;
        }
        //拷贝数据
        UserSignInVo userSignInVo = Copy(userSignIn);
        return userSignInVo;
    }

    /**
     *  拷贝数据
     * @param userSignIn
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private UserSignInVo Copy(UserSignIn userSignIn) {
        //创建对象
        UserSignInVo userSignInVo = new UserSignInVo();
        //拷贝数据
        BeanUtils.copyProperties(userSignIn,userSignInVo);
        return userSignInVo;
    }

    /**
     * 获取用户id
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private Long getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断是否登录
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }
}
